package date0701;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 定义一个可以偷懒的工具类 ( 但不考虑该类的设计 )
 */
public class JdbcUtil {
	
	// Oracle
	private static String driverClassName = "oracle.jdbc.driver.OracleDriver"  ;
	private static String url = "jdbc:oracle:thin:@localhost:1521:ecut" ;
	private static String user = "ecuter" ;
	private static String password = "ecuter" ;
	
	/*
	// MySQL
	private static String driverClassName = "com.mysql.cj.jdbc.Driver"  ;
	private static String url = "jdbc:mysql://localhost:3306/ecut?serverTimezone=Asia/Shanghai&useSSL=false" ;
	private static String user = "ecuter" ;
	private static String password = "ecuter" ;
	*/
	
	// 定义用来获得数据库连接的方法
	public static Connection connect(){
		try {
			Class.forName( driverClassName );
		} catch (ClassNotFoundException e) {
			System.err.println( "驱动类[ " + driverClassName + " ]加载失败" );
			e.printStackTrace();
		} 
		
		Connection connection = null ;
		try {
			connection = DriverManager.getConnection( url , user , password );
		} catch (SQLException e) {
			System.err.println( "建立数据库连接时发生故障" );
			e.printStackTrace();
		}
		return connection ;
	}
	
	// 用来创建 Statement 对象的方法
	public static Statement create( Connection connection ) {
		try {
			return connection.createStatement();
		} catch (SQLException cause) {
			RuntimeException re = new RuntimeException( "创建Statement对象时发生故障" , cause );
			throw re ;
		}
	}

	// 定义关闭数据库连接的方法
	public static void close( Connection connection ) {
		if( connection != null ) {
			try {
				connection.close();
			} catch (SQLException e) {
				System.err.println( "关闭数据库连接时发生故障" );
				e.printStackTrace();
			}
		}
	}
	
	// 定义关闭数据库连接的方法
	public static void close( Statement statement ) {
			if( statement != null ) {
				try {
					statement.close();
				} catch (SQLException e) {
					System.err.println( "关闭 Statement 对象时发生故障" );
					e.printStackTrace();
				}
			}
	}
	
	// 读取用户输入的SQL语句
	public static String input() {
		
		StringBuffer buffer = new StringBuffer();
		
		Reader reader = new InputStreamReader( System.in ) ; // 将 标准输入流 包装成 字符输入流
		BufferedReader br = new BufferedReader( reader ); // 将 字符输入流 保证成 带有缓冲功能的 字符输入流
		
		try {
			System.out.print( "SQL> " );
			int count = 1 ;
			while( true ) {
				String s = br.readLine(); // 每次读取一行
				buffer.append( s ); // 将本行读取到的数据追加到字符缓冲区中
				if( s.endsWith( ";" ) ) {
					break ;
				}
				System.out.print( ++count + " "); // 像 SQL*Plus 一样输出行数统计
			}
			
			br.close(); // IOException
			reader.close(); // IOException
		} catch( IOException e ) {
			e.printStackTrace();
		}
		
		buffer.deleteCharAt( buffer.lastIndexOf( ";" ) ); // 剔除末尾的分号
		
		return buffer.toString();
	}
		
}
